package cn.aukw.todolist.utils;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.util.Log;


import cn.aukw.todolist.bean.ListBean;
import cn.aukw.todolist.sqlite.SQLiteHelper;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;

public class DBUtils {
    private static DBUtils instance = null;
    private static SQLiteHelper helper;
    private static SQLiteDatabase db;


    public DBUtils(Context context) {
        helper = new SQLiteHelper(context);
        db = helper.getWritableDatabase();
    }

    public static DBUtils getInstance(Context context) {
        if (instance == null) {
            instance = new DBUtils(context);
        }
        return instance;
    }


    public List<ListBean> queryList() {
        List<ListBean> list = new ArrayList<>();
        String sql = "SELECT * FROM " + SQLiteHelper.LIST_NAME + " ORDER BY isCompleted ASC, id DESC";

        try (Cursor cursor = db.rawQuery(sql, null)) { // 自动管理 Cursor 资源
            if (cursor != null) {
                // 获取列索引，避免重复调用 getColumnIndex
                int idIndex = cursor.getColumnIndex("id");
                int titleIndex = cursor.getColumnIndex("title");
                int contentIndex = cursor.getColumnIndex("content");
                int timeIndex = cursor.getColumnIndex("time");
                int isCompletedIndex = cursor.getColumnIndex("isCompleted");

                // 检查列索引有效性
                if (idIndex == -1 || titleIndex == -1 || contentIndex == -1 || timeIndex == -1 || isCompletedIndex == -1) {
                    throw new IllegalArgumentException("Invalid column name in the query result.");
                }

                // 遍历 Cursor
                while (cursor.moveToNext()) {
                    ListBean bean = new ListBean();
                    bean.setId(cursor.getInt(idIndex));
                    bean.setTitle(cursor.getString(titleIndex));
                    bean.setContent(cursor.getString(contentIndex));
                    bean.setTime(cursor.getString(timeIndex));
                    bean.setCompleted(cursor.getInt(isCompletedIndex) == 1); // 设置完成状态
                    list.add(bean);
                }
            }
        } catch (Exception e) {
            // 记录日志，方便排查
            Log.e("DBUtils", "Error querying list: ", e);
        }
        return list;
    }

    public boolean deleteList(int id) {
        boolean delSuccess = false;
        int rows = db.delete(SQLiteHelper.LIST_NAME, " id=?", new String[]{id + ""});
        if (rows > 0) {
            delSuccess = true;
        }
        return delSuccess;
    }

    public static final String getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        return sdf.format(new Date());
    }

    public boolean saveList(String title, String content, String time) {
        boolean saveSuccess = false;
        ContentValues cv = new ContentValues();
        cv.put("title", title);
        cv.put("content", content);
        cv.put("time", time);
        cv.put("isCompleted", 0); // 默认未完成
        long rowId = db.insert(SQLiteHelper.LIST_NAME, null, cv);
        if (rowId > 0) {
            saveSuccess = true;
        }
        return saveSuccess;
    }

    public boolean updateList(int id, String title, String content, String time) {
        boolean updateSuccess = false;
        ContentValues cv = new ContentValues();
        cv.put("title", title);
        cv.put("content", content);
        cv.put("time", time);
        int rows = db.update(SQLiteHelper.LIST_NAME, cv, "id=?", new String[]{id + ""});
        if (rows > 0) {
            updateSuccess = true;
        }
        return updateSuccess;
    }

    public boolean updateListCompleted(int id, boolean isCompleted) {
        boolean updateSuccess = false;
        ContentValues cv = new ContentValues();
        cv.put("isCompleted", isCompleted ? 1 : 0);
        int rows = db.update(SQLiteHelper.LIST_NAME, cv, "id=?", new String[]{id + ""});
        if (rows > 0) {
            updateSuccess = true;
        }
        return updateSuccess;
    }
}
